package com.shunwang.query_sql.nl2Sql.service.impl;

import com.shunwang.query_sql.nl2Sql.mapper.Nl2SqlMapper;
import com.shunwang.query_sql.nl2Sql.service.Nl2SqlService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class Nl2SqlServiceImpl implements Nl2SqlService {

    private final Nl2SqlMapper nl2SqlMapper;

    @Override
    public List<Map<String, Object>> processQuery(String sql) {
        // 参数校验
        if (!StringUtils.hasText(sql)) {
            log.warn("SQL查询语句为空");
            return Collections.emptyList();
        }

        try {
            // 执行查询
            log.debug("执行SQL查询: {}", sql);
            List<Map<String, Object>> result = nl2SqlMapper.executeQuery(sql);
            log.debug("查询结果行数: {}", result != null ? result.size() : 0);
            return result != null ? result : Collections.emptyList();
        } catch (DataAccessException e) {
            log.error("数据库查询异常: {}", e.getMessage(), e);
            throw new RuntimeException("数据库查询执行失败: " + e.getMessage(), e);
        } catch (Exception e) {
            log.error("查询执行未知异常: {}", e.getMessage(), e);
            throw new RuntimeException("查询执行失败: " + e.getMessage(), e);
        }
    }
}